<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of User
 *
 * @author QuangKhoi
 */
class User {
    //put your code here
    public $idUser;
    public $idAvatar;
    public $idDevice;
    public $token;
    public $tokenExp;
    public $nameUser;
    public $password;
    public $email;
    public $status;
    
    public function __get($name) {
        return $this->$name;
    }
    
    public function __set($name, $value) {
        $this->$name = $value;
    }
    
    public static function withData($idDevice, $nameUser, $password, $email) {
            $instance = new self();
            $instance->idDevice = $idDevice;
            $instance->nameUser=$nameUser;
            $instance->password=$password;
            $instance->email=$email;
            return $instance;
    }

    public function __construct() {
        
    }
    
    public static function withEmail($email) {
        if ($email == '') {
            $controller = new ErrorController(new Error(), new ErrorView, 
                    "500", "No email provided");
                $controller->returnError();
            die();
        }
        $instance = new self();
        $db = Database::getInstance();
        $query = "SELECT * FROM Users WHERE email = '$email'";
        $result = $db->query($query);
        if ($result->returnCode == 200) {
            if ($result->dataTable->numOfRow == 1) {
                $rows = $result->dataTable->rows[0];
                $instance->idUser = $rows["idUser"];
                $instance->idAvatar = $rows["idAvatar"];
                $instance->idDevice = $rows["idDevice"];
                $instance->token = $rows["token"];
                $instance->tokenExp = $rows["tokenExp"];
                $instance->nameUser = $rows["nameUser"];
                $instance->password = $rows["password"];
                $instance->email = $rows["email"];
                $instance->status = $rows["status"];
            }
            else {
                $controller = new ErrorController(new Error(), new ErrorView, 
                    "404", "Not found any user with provided email");
                $controller->returnError();
            }
        }
        else {
            $controller = new ErrorController(new Error(), new ErrorView, 
                    $result->returnCode, $result->message);
            $controller->returnError();
        }
        return $instance;
    }
}

?>
